package com.sia.springcloud.heartbeat;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sia.springcloud.mapper.DeviceMapper;
import com.sia.springcloud.model.Device;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Author: Sirius
 * @Date: 2021/12/30 12:30
 * @Description: 心跳检测任务
 * <p>
 * 需要在application配置文件中设置心跳参数
 * heartbeatId：心跳id，自动生成
 * instance-id：eureka中注册的实例名称，核心微服务需要通过该名称获取完成url，进行请求转发
 * protocol-name：协议名，需要在配置文件中配置，通过该项识别该微服务能处理的数采协议的类型
 * deviceCount：该协议微服务中正在进行数采的设备个数
 * frequency：心跳频率，默认值为5秒每次
 * <p>
 * 2022/5/9 注释掉@Component，防止自动注入，避免使用心跳检测
 **/
@Slf4j
//@Component
public class HeartbeatJob extends QuartzJobBean {


    @Resource
    private RestTemplate restTemplate;


    private QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();

    @Resource
    private DeviceMapper deviceMapper;


    /**
     * 心跳检测任务
     *
     * @param context
     * @throws JobExecutionException
     */
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        /**
         * 这里不需要进行推迟20秒开始，因为能够发送出去就说明双方已经连接上eureka
         */

        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String heartbeatId = (String) jobDataMap.get("heartbeatId");
        String instanceId = (String) jobDataMap.get("instanceId");
        String protocolName = (String) jobDataMap.get("protocolName");
        String destUrl = (String) jobDataMap.get("destUrl");

        MultiValueMap<String, String> instanceInfo = new LinkedMultiValueMap<>();

        //查询该数采微服务中正处于数采状态的设备数量
        deviceQueryWrapper.eq("collect", 1);
        deviceQueryWrapper.eq("microservice", heartbeatId);
        Integer deviceCount = deviceMapper.selectCount(deviceQueryWrapper);

        long time = System.currentTimeMillis();
        instanceInfo.add("heartbeatId", heartbeatId);
        instanceInfo.add("instanceId", instanceId);
        instanceInfo.add("protocolName", protocolName);
        instanceInfo.add("deviceCount", String.valueOf(deviceCount));
        instanceInfo.add("time", String.valueOf(time));

        try {
            restTemplate.postForObject(destUrl, instanceInfo, String.class);
            log.info("heartbeat--正常--{}--{}", instanceId, heartbeatId);
        } catch (Exception e) {
            log.info("heartbeat--失败");
        }
    }


}
